<script setup lang="ts">
import { ref, nextTick, onMounted } from 'vue'
import { marked } from 'marked'
import hljs from 'highlight.js'
import 'highlight.js/styles/github.css'
import {
  getConversation,
  getMessages,
  deleteConversation,
  newConversation
} from '@/api/aiController'
import { type MarkedOptions } from 'marked'

// 配置 marked 支持代码高亮和表格
marked.setOptions({
  highlight: function(code: string, lang: string) {
    if (lang && hljs.getLanguage(lang)) {
      return hljs.highlight(code, { language: lang }).value
    }
    return hljs.highlightAuto(code).value
  },
  gfm: true, // GitHub Flavored Markdown
  breaks: true, // 允许回车换行
  headerIds: true, // 为标题添加ID
  mangle: false, // 不转义标题中的内容
  pedantic: false, // 不容错模式
  sanitize: false, // 不净化输出
  smartLists: true, // 使用更智能的列表行为
  smartypants: true, // 使用更智能的标点符号
  xhtml: false // 不自闭合标签
} as MarkedOptions)

// 会话类型
type Conversation = {
  conversationId: string;
  title: string;
  isTemp?: boolean; // 标记是否为临时会话
}
// 定义后端返回的消息结构（根据实际情况调整）
interface BackendMessage {
  messageType: 'USER' | 'ASSISTANT';
  text: string;
  // 可以根据你的后端API返回的实际字段来定义
  // 例如：id?: string; metadata?: Record<string, any>; toolCalls?: any[]; media?: any[];
}

const conversations = ref<Conversation[]>([])
const messages = ref<{ role: 'user' | 'ai', content: string, loading?: boolean }[]>([])
const input = ref('')
const loading = ref(false)
const chatContainer = ref<HTMLElement | null>(null)
const sidebarOpen = ref(true)
const conversationId = ref('') // 当前会话ID
const currentPage = ref(1)
const pageSize = ref(10)
const loadingHistory = ref(false)
const hasMoreHistory = ref(true)
const loadingConversations = ref(false)
const isTempConversation = ref(false) // 标记当前是否为临时会话
const selectedAssistant = ref<string | null>(null)
const isAIResponding = ref(false) // 标记AI是否正在回复
const eventSource = ref<EventSource | null>(null) // 保存EventSource实例，用于中断回复

const assistantList = [
  { type: 'love', label: '恋爱助手', icon: '💌', placeholder: '请输入你的恋爱困惑...' },
  { type: 'psychology', label: '心理助手', icon: '🧘', placeholder: '请输入你的心理问题...' }
]

// 获取会话列表
const loadConversations = async () => {
  loadingConversations.value = true
  try {
    const result = await getConversation()
    if (result?.data?.data && Array.isArray(result.data.data)) {
      // 保存临时会话
      const tempConv = conversations.value.find(c => c.isTemp)

      conversations.value = result.data.data.map((id: string) => ({ conversationId: id, title: `会话 ${id.slice(-6)}` }))

      // 如果有临时会话且不在已加载的会话中，添加回来
      if (tempConv && !conversations.value.some(c => c.conversationId === tempConv.conversationId)) {
        conversations.value.unshift(tempConv)
      }

      if (!conversationId.value && conversations.value.length > 0) {
        conversationId.value = conversations.value[0].conversationId
        isTempConversation.value = !!conversations.value[0].isTemp
        loadHistory(true)
      }
    }
  } catch (e) {
    console.error('加载会话列表失败', e)
  } finally {
    loadingConversations.value = false
  }
}

// 加载历史消息
const loadHistory = async (reset = false) => {
  console.log('加载历史消息:', conversationId.value)

  if (loadingHistory.value || !conversationId.value) {
    console.log('跳过加载:', loadingHistory.value, conversationId.value)
    return
  }

  if (reset) {
    messages.value = []
    currentPage.value = 1
    hasMoreHistory.value = true
  }

  // 如果是临时会话，不加载历史
  if (isTempConversation.value) {
    console.log('临时会话不加载历史')
    return
  }

  loadingHistory.value = true
  try {
    console.log('请求会话消息:', conversationId.value, currentPage.value, pageSize.value)
    const result = await getMessages({
      conversationId: conversationId.value,
      current: currentPage.value,
      size: pageSize.value
    })

    console.log('获取消息结果:', result?.data?.data?.length || 0)

    if (result?.data?.data && Array.isArray(result.data.data) && result.data.data.length > 0) {
      const historyMessages = result.data.data.map((msg: BackendMessage) => ({
        role: msg.messageType === 'USER' ? 'user' : 'ai' as 'user' | 'ai',
        content: msg.text,
        loading: false
      }))

      // 使用新数组替换或合并
      if (reset) {
        messages.value = [...historyMessages]
      } else {
        messages.value = [...historyMessages, ...messages.value]
      }

      // 如果是第一页且有用户消息，更新会话标题为第一条用户消息
      if (reset && result.data.data.length > 0) {
        const firstUserMsg = result.data.data.find((msg: BackendMessage) => msg.messageType === 'USER')
        if (firstUserMsg) {
          updateConversationTitle(conversationId.value, firstUserMsg.text || '')
        }
      }

      hasMoreHistory.value = result.data.data.length === pageSize.value
      currentPage.value++

      // 确保滚动到底部
      nextTick(() => {
        chatContainer.value?.scrollTo({ top: chatContainer.value.scrollHeight, behavior: 'smooth' })
      })
    } else {
      hasMoreHistory.value = false
    }
  } catch (error) {
    console.error('加载历史消息失败:', error)
    hasMoreHistory.value = false
  } finally {
    loadingHistory.value = false
  }
}

// 更新会话标题为用户消息内容
const updateConversationTitle = (id: string, content: string) => {
  const maxLength = 20
  // 截取内容作为标题，最多显示20个字符
  const title = content.length > maxLength ? content.substring(0, maxLength) + '...' : content
  const index = conversations.value.findIndex(c => c.conversationId === id)
  if (index !== -1) {
    conversations.value[index].title = title
  }
}

const loadMoreHistory = () => {
  loadHistory()
}

const selectConversation = (id: string) => {
  console.log('选择会话:', id)
  // 如果AI正在回复，不允许切换会话
  if (isAIResponding.value) return
  
  if (conversationId.value === id) return

  // 无论什么情况，先清空当前消息
  messages.value = []

  // 设置当前会话ID
  conversationId.value = id

  // 找到选中的会话
  const selectedConv = conversations.value.find(c => c.conversationId === id)

  if (!selectedConv) {
    console.error('找不到指定的会话:', id)
    return
  }

  isTempConversation.value = !!selectedConv.isTemp
  console.log('是否临时会话:', isTempConversation.value)

  // 如果不是临时会话，加载历史消息
  if (!isTempConversation.value) {
    loadHistory(true)
  }
}

// 创建新会话 - 仅生成UUID，不实际创建后端会话
const createNewConversation = async () => {
  const res = await newConversation()
  const tempId = res?.data?.data ? String(res.data.data) : `temp-${Date.now()}`
  const tempTitle = '新会话'

  // 创建临时会话并添加到列表最前面
  conversations.value.unshift({
    conversationId: tempId,
    title: tempTitle,
    isTemp: true
  })

  // 选择这个临时会话
  conversationId.value = tempId
  isTempConversation.value = true
  messages.value = []
}

// 删除会话
const deleteCurrentConversation = async (id: string, event?: MouseEvent) => {
  // 阻止事件冒泡，避免触发会话选择
  if (event) {
    event.stopPropagation()
  }

  if (id && !isTempConversation.value) {
    try {
      // 调用删除会话API
      await deleteConversation({ conversationId: id })

      // 从会话列表中移除
      const index = conversations.value.findIndex(c => c.conversationId === id)
      if (index !== -1) {
        conversations.value.splice(index, 1)
      }

      // 如果删除的是当前会话，选择其他会话或创建新会话
      if (id === conversationId.value) {
        if (conversations.value.length > 0) {
          // 选择第一个会话
          selectConversation(conversations.value[0].conversationId)
        } else {
          // 如果没有会话了，创建一个新的临时会话
          createNewConversation()
        }
      }
    } catch (error) {
      console.error('删除会话失败:', error)
    }
  } else if (isTempConversation.value) {
    // 如果是临时会话，直接从列表中移除
    const index = conversations.value.findIndex(c => c.conversationId === id)
    if (index !== -1) {
      conversations.value.splice(index, 1)
    }

    // 如果删除的是当前会话，选择其他会话或创建新会话
    if (id === conversationId.value) {
      if (conversations.value.length > 0) {
        selectConversation(conversations.value[0].conversationId)
      } else {
        createNewConversation()
      }
    }
  }
}

// 中断AI回复
const stopAIResponse = () => {
  if (eventSource.value) {
    eventSource.value.close()
    eventSource.value = null
    isAIResponding.value = false
    
    // 标记最后一条消息已加载完成
    if (messages.value.length > 0 && messages.value[messages.value.length - 1].loading) {
      messages.value[messages.value.length - 1].loading = false
    }
  }
}

const baseUrl = import.meta.env.VITE_APP_API_URL
const sendMessage = async () => {
  if (!input.value.trim()) return
  const question = input.value

  // 保存当前输入内容
  const userMessage = question
  input.value = ''

  // 添加用户消息到界面
  messages.value.push({ role: 'user', content: userMessage })

  loading.value = true
  isAIResponding.value = true

  // 根据助手类型选择不同接口
  let url = ''
  if (selectedAssistant.value === 'love') {
    url = `${baseUrl}/api/ais/call/love?conversationId=${conversationId.value}&question=${encodeURIComponent(userMessage)}`
  } else if (selectedAssistant.value === 'psychology') {
    url = `${baseUrl}/api/ais/call/psychologist?conversationId=${conversationId.value}&question=${encodeURIComponent(userMessage)}`
  } else {
    url = `${baseUrl}/api/ais/call?conversionId=${conversationId.value}&question=${encodeURIComponent(userMessage)}`
  }

  // 如果存在之前的EventSource，先关闭
  if (eventSource.value) {
    eventSource.value.close()
  }
  
  eventSource.value = new EventSource(url)
  let aiMsg = ''
  messages.value.push({ role: 'ai', content: '', loading: true })

  eventSource.value.onmessage = (event) => {
    aiMsg += event.data
    messages.value[messages.value.length - 1].content = aiMsg
    nextTick(() => {
      chatContainer.value?.scrollTo({ top: chatContainer.value.scrollHeight, behavior: 'smooth' })
    })
  }

  eventSource.value.onerror = () => {
    loading.value = false
    isAIResponding.value = false
    messages.value[messages.value.length - 1].loading = false
    if (eventSource.value) {
      eventSource.value.close()
      eventSource.value = null
    }

    // 刷新会话列表以获取新创建的会话
    loadConversations().then(() => {
      // 如果是临时会话，更新标题并移除临时标记
      if (isTempConversation.value) {
        // 在会话列表中找到当前会话的索引
        const index = conversations.value.findIndex(c => c.conversationId === conversationId.value)
        if (index !== -1) {
          // 将第一条用户消息作为标题
          updateConversationTitle(conversationId.value, userMessage)
          // 移除临时标记
          conversations.value[index].isTemp = false
          isTempConversation.value = false
        }
      }
    })
  }

  eventSource.value.onopen = () => {
    loading.value = false
    messages.value[messages.value.length - 1].loading = false
  }
}

const copySingle = async (content: string) => {
  try {
    await navigator.clipboard.writeText(content)
  } catch {
    const el = document.createElement('textarea')
    el.value = content
    document.body.appendChild(el)
    el.select()
    document.execCommand('copy')
    document.body.removeChild(el)
  }
}

const copyAll = async () => {
  const text = messages.value.map(m => (m.role === 'user' ? '🧑 用户：' : '🤖 AI：') + m.content).join('\n\n')
  try {
    await navigator.clipboard.writeText(text)
  } catch {
    const el = document.createElement('textarea')
    el.value = text
    document.body.appendChild(el)
    el.select()
    document.execCommand('copy')
    document.body.removeChild(el)
  }
}

const selectAssistant = (type: string) => {
  selectedAssistant.value = type
}
const cancelAssistant = () => {
  selectedAssistant.value = null
}

onMounted(() => {
  loadConversations()
})
</script>

<template>
  <div class="chat-layout">
    <aside :class="['chat-sidebar', { closed: !sidebarOpen }]">
      <div class="sidebar-header">
        <span>会话列表</span>
        <button class="toggle-btn" @click="sidebarOpen = !sidebarOpen" title="收起/展开">
          <span v-if="sidebarOpen">«</span>
          <span v-else>»</span>
        </button>
      </div>
      <div v-show="sidebarOpen" class="sidebar-content">
        <div v-if="loadingConversations" class="sidebar-loading">加载会话中...</div>
        <div v-else>
          <button class="new-chat-btn" @click="createNewConversation" :disabled="isAIResponding">
            <span class="plus-icon">+</span> 新建会话
          </button>
          <div v-if="conversations.length === 0" class="no-conversations">
            暂无会话，请发送消息开始对话
          </div>
          <div v-for="conv in conversations" :key="conv.conversationId" :class="['sidebar-conv', { active: conv.conversationId === conversationId, temp: conv.isTemp }]">
            <div class="conv-click-area" @click="selectConversation(conv.conversationId)">
              <span class="sidebar-conv-title">{{ conv.title }}</span>
              <span v-if="conv.isTemp" class="temp-badge">未保存</span>
              <span v-if="isAIResponding && conv.conversationId !== conversationId" class="disabled-icon" title="AI回复中，无法切换会话">🚫</span>
            </div>
            <button class="delete-btn" @click="deleteCurrentConversation(conv.conversationId, $event)" title="删除会话" :disabled="isAIResponding && conv.conversationId === conversationId">×</button>
          </div>
        </div>
      </div>
    </aside>
    <main class="chat-main">
      <div class="chat-title-bar">
        <div class="chat-title">AI 智能助手</div>
        <div class="title-actions">
          <button v-if="isAIResponding" class="stop-btn" @click="stopAIResponse" title="停止生成">停止生成</button>
          <button class="copy-all-btn" @click="copyAll" title="复制全部对话" v-if="messages.length > 0">复制全部</button>
        </div>
      </div>
      <div class="chat-container" ref="chatContainer">
        <div v-if="loadingHistory && messages.length === 0" class="loading-history">
          <div class="loading-spinner"></div>
          <span>加载历史消息中...</span>
        </div>
        <div v-if="!loadingHistory && messages.length === 0" class="empty-chat">
          <div class="empty-chat-icon">💬</div>
          <div class="empty-chat-text">
            <p v-if="isTempConversation">这是新会话，请输入您的问题开始对话</p>
            <p v-else>请输入您的问题，AI 将为您提供帮助</p>
          </div>
        </div>
        <div v-if="hasMoreHistory && messages.length > 0" class="load-more" @click="loadMoreHistory">
          <span v-if="!loadingHistory">加载更多</span>
          <span v-else>加载中...</span>
        </div>
        <div v-for="(msg, idx) in messages" :key="idx" :class="['chat-msg', msg.role]">
          <span class="avatar">{{ msg.role === 'user' ? '🧑' : '🤖' }}</span>
          <span v-if="msg.role === 'ai'" class="content ai-content">
            <span v-html="marked(msg.content)"></span>
            <span v-if="msg.loading" class="loading-dot">
              <span class="dot"></span><span class="dot"></span><span class="dot"></span>
            </span>
            <button v-if="!msg.loading && msg.content" class="copy-btn" @click="copySingle(msg.content)" title="复制此条内容">复制</button>
          </span>
          <span v-else class="content">{{ msg.content }}</span>
        </div>
      </div>
      <div class="assistant-selector" v-if="!selectedAssistant">
        <div
          v-for="assistant in assistantList"
          :key="assistant.type"
          class="assistant-card"
          @click="selectAssistant(assistant.type)"
        >
          <span class="assistant-icon">{{ assistant.icon }}</span>
          <span class="assistant-label">{{ assistant.label }}</span>
        </div>
      </div>
      <div class="assistant-merge-bar" v-else>
        <div class="assistant-card selected">
          <span class="assistant-icon">{{ assistantList.find(a => a.type === selectedAssistant)?.icon }}</span>
          <span class="assistant-label">{{ assistantList.find(a => a.type === selectedAssistant)?.label }}</span>
        </div>
        <button class="assistant-cancel-btn" @click="cancelAssistant" title="取消">×</button>
      </div>
      <div class="chat-input-bar">
        <input
          v-model="input"
          @keyup.enter="sendMessage"
          :disabled="loading"
          :placeholder="selectedAssistant ? assistantList.find(a => a.type === selectedAssistant)?.placeholder : '请输入你的问题...'"
        />
        <button @click="sendMessage" :disabled="loading || !input.trim()">发送</button>
      </div>
    </main>
  </div>
</template>

<style scoped>
html, body, #app {
  height: 100%;
  margin: 0;
  padding: 0;
}
.chat-layout {
  display: flex;
  height: 100vh;
  background: #f4f6fa;
  border-radius: 0;
  box-shadow: none;
  overflow: hidden;
  max-width: 100vw;
  margin: 0;
  font-family: 'Helvetica Neue', Helvetica, 'PingFang SC', 'Hiragino Sans GB', 'Microsoft YaHei', '\\5FAE软雅黑', Arial, sans-serif;
}
.chat-sidebar {
  width: 240px;
  background: #fff;
  border-right: 1px solid #e0e0e0;
  transition: width 0.3s cubic-bezier(.4,2,.6,1), min-width 0.3s;
  min-width: 60px;
  display: flex;
  flex-direction: column;
  position: relative;
  height: 100vh;
  border-radius: 0;
}
.chat-sidebar.closed {
  width: 36px;
  min-width: 36px;
}
.sidebar-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 12px 8px 16px;
  font-weight: bold;
  color: #3a7afe;
  border-bottom: 1px solid #f0f0f0;
  background: #f7faff;
}
.toggle-btn {
  background: none;
  border: none;
  font-size: 1.2rem;
  color: #3a7afe;
  cursor: pointer;
  outline: none;
  padding: 0 4px;
}
.sidebar-content {
  flex: 1;
  overflow-y: auto;
  padding: 8px 0;
}
.new-chat-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  width: calc(100% - 16px);
  margin: 8px auto;
  padding: 10px;
  background: #3a7afe;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 0.95rem;
  transition: background 0.2s;
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);
  font-weight: 500;
}
.new-chat-btn:hover {
  background: #2563eb;
}
.new-chat-btn:active {
  transform: translateY(1px);
  box-shadow: 0 0 2px rgba(0,0,0,0.05);
}
.plus-icon {
  font-size: 1.2rem;
  margin-right: 6px;
}
.no-conversations {
  padding: 16px;
  text-align: center;
  color: #6b7280;
  font-size: 0.9rem;
}
.sidebar-conv {
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid #f5f5f5;
  color: #555;
  font-size: 1rem;
  transition: background 0.2s, color 0.2s;
  position: relative;
  padding: 0;
}
.sidebar-conv-content {
  flex: 1;
  display: flex;
  align-items: center;
  padding: 12px 8px 12px 16px;
}
.sidebar-conv.active {
  background: #e6f0ff;
  color: #2563eb;
  font-weight: bold;
}
.sidebar-conv-title {
  flex: 1;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.delete-btn {
  background: none;
  border: none;
  color: #999;
  font-size: 1.2rem;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.2s, color 0.2s;
  padding: 0 8px;
  margin-right: 8px;
  height: 100%;
  display: flex;
  align-items: center;
}
.sidebar-conv:hover .delete-btn {
  opacity: 1;
}
.delete-btn:hover {
  color: #f56565;
}
.delete-icon {
  font-size: 1.2rem;
  font-weight: bold;
}
.chat-main {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fff;
  border-radius: 0;
  min-width: 0;
  height: 100vh;
}
.chat-title-bar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24px 24px 0 24px;
}
.chat-title {
  font-size: 2rem;
  font-weight: bold;
  color: #3a7afe;
  letter-spacing: 2px;
}
.title-actions {
  display: flex;
  gap: 10px;
  align-items: center;
}
.copy-all-btn {
  background: #e6f0ff;
  color: #2563eb;
  border: none;
  border-radius: 8px;
  padding: 6px 18px;
  font-size: 1rem;
  cursor: pointer;
  transition: background 0.2s;
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);
  font-weight: 500;
}
.copy-all-btn:hover {
  background: #3a7afe;
  color: #fff;
}
.copy-all-btn:active {
  transform: translateY(1px);
  box-shadow: 0 0 2px rgba(0,0,0,0.05);
}
.stop-btn {
  background: #ff4d4f;
  color: white;
  border: none;
  border-radius: 8px;
  padding: 6px 18px;
  font-size: 1rem;
  cursor: pointer;
  transition: background 0.2s;
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);
  font-weight: 500;
}
.stop-btn:hover {
  background: #ff7875;
}
.stop-btn:active {
  transform: translateY(1px);
  box-shadow: 0 0 2px rgba(0,0,0,0.05);
}
.disabled-icon {
  font-size: 1rem;
  color: #ff4d4f;
  margin-left: 8px;
}
.chat-container {
  flex: 1;
  overflow-y: auto;
  padding: 0 24px;
  margin-bottom: 0;
  max-height: none;
}
.empty-chat {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: #6b7280;
}
.empty-chat-icon {
  font-size: 4rem;
  margin-bottom: 16px;
  color: #3a7afe;
}
.empty-chat-text {
  font-size: 1.2rem;
  max-width: 80%;
  text-align: center;
}
.chat-msg {
  display: flex;
  align-items: flex-start;
  margin: 12px 0;
}
.chat-msg.user {
  flex-direction: row-reverse;
}
.chat-msg .avatar {
  font-size: 1.5rem;
  margin: 0 8px;
}
.chat-msg .content {
  background: #f5f7fa;
  border-radius: 8px;
  padding: 10px 16px;
  max-width: 70%;
  word-break: break-all;
  font-size: 1rem;
  color: #333;
  position: relative;
  box-shadow: 0 1px 2px rgba(0,0,0,0.05);
}
.chat-msg.user .content {
  background: #e6f0ff;
  color: #2563eb;
}
.ai-content {
  position: relative;
  display: inline-block;
  padding-left: 16px;
  border-radius: 10px;
  background: #f8fbff;
  box-shadow: 0 2px 8px #e6f0ffcc;
  margin-bottom: 2px;
}
.ai-content::before {
  content: '';
  position: absolute;
  left: 0;
  top: 12px;
  bottom: 12px;
  width: 4px;
  border-radius: 4px;
  background: linear-gradient(180deg, #3a7afe 60%, #a5d8ff 100%);
}

/* 强化Markdown样式 */
.ai-content h1, .ai-content h2, .ai-content h3, .ai-content h4, .ai-content h5, .ai-content h6 {
  margin: 1rem 0 0.5rem;
  color: #2563eb;
  font-weight: bold;
  line-height: 1.4;
}
.ai-content h1 { font-size: 1.6rem; border-bottom: 1px solid #eaecef; padding-bottom: 0.3rem; }
.ai-content h2 { font-size: 1.4rem; border-bottom: 1px solid #eaecef; padding-bottom: 0.3rem; }
.ai-content h3 { font-size: 1.2rem; }
.ai-content h4 { font-size: 1.1rem; }
.ai-content h5 { font-size: 1rem; }
.ai-content h6 { font-size: 0.9rem; }

.ai-content strong {
  font-weight: 600;
  color: #111827;
}

.ai-content em {
  font-style: italic;
  color: #4b5563;
}

.ai-content blockquote {
  padding: 0.5rem 1rem;
  margin: 1rem 0;
  color: #6b7280;
  border-left: 4px solid #d1d5db;
  background: #f9fafb;
  border-radius: 0 4px 4px 0;
}

.ai-content hr {
  height: 1px;
  background-color: #e5e7eb;
  border: none;
  margin: 1.5rem 0;
}

.ai-content del {
  text-decoration: line-through;
  color: #9ca3af;
}

.ai-content table {
  border-collapse: collapse;
  margin: 16px 0;
  width: 100%;
  font-size: 0.95rem;
  box-shadow: 0 2px 8px #e6f0ff60;
  border-radius: 6px;
  overflow: hidden;
}

.ai-content th, .ai-content td {
  border: 1px solid #e0e0e0;
  padding: 10px 16px;
  text-align: left;
}

.ai-content th {
  background: #f5f7fa;
  color: #2563eb;
  font-weight: 600;
}

.ai-content tr:nth-child(even) {
  background-color: #f8fafc;
}

.ai-content pre {
  margin: 1rem 0;
  border-radius: 6px;
  overflow: hidden;
}

.ai-content pre code {
  display: block;
  padding: 16px;
  background: #f6f8fa;
  border-radius: 8px;
  font-size: 0.95rem;
  overflow-x: auto;
  box-shadow: 0 2px 8px #e6f0ff60;
  line-height: 1.5;
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
}

.ai-content code:not(pre code) {
  background: #f5f7fa;
  padding: 2px 5px;
  border-radius: 3px;
  font-size: 0.9em;
  color: #e11d48;
  font-family: 'SFMono-Regular', Consolas, 'Liberation Mono', Menlo, monospace;
}

.ai-content a {
  color: #3a7afe;
  text-decoration: none;
  border-bottom: 1px dotted #3a7afe;
  transition: color 0.2s, border-bottom 0.2s;
}

.ai-content a:hover {
  color: #1d4ed8;
  border-bottom: 1px solid #1d4ed8;
}

.ai-content ul, .ai-content ol {
  margin: 0.5rem 0 0.5rem 1.5rem;
  padding-left: 0.5rem;
}

.ai-content li {
  margin-bottom: 0.3rem;
  line-height: 1.6;
}

.ai-content img {
  max-width: 100%;
  border-radius: 6px;
  margin: 0.5rem 0;
}

/* 高亮块 */
.ai-content mark {
  background-color: #fef3c7;
  color: #92400e;
  padding: 0.1rem 0.2rem;
  border-radius: 3px;
}

/* 任务列表 */
.ai-content input[type="checkbox"] {
  margin-right: 0.5rem;
}
.copy-btn {
  position: absolute;
  right: 8px;
  top: 8px;
  background: #e6f0ff;
  color: #2563eb;
  border: none;
  border-radius: 6px;
  padding: 2px 10px;
  font-size: 0.95rem;
  cursor: pointer;
  transition: background 0.2s;
  opacity: 0.7;
}
.copy-btn:hover {
  background: #3a7afe;
  color: #fff;
  opacity: 1;
}
.loading-dot {
  display: inline-block;
  margin-left: 8px;
  vertical-align: middle;
}
.loading-dot .dot {
  display: inline-block;
  width: 6px;
  height: 6px;
  margin: 0 1px;
  background: #3a7afe;
  border-radius: 50%;
  animation: blink 1.2s infinite both;
}
.loading-dot .dot:nth-child(2) {
  animation-delay: 0.2s;
}
.loading-dot .dot:nth-child(3) {
  animation-delay: 0.4s;
}
@keyframes blink {
  0%, 80%, 100% { opacity: 0.2; }
  40% { opacity: 1; }
}
.chat-input-bar {
  display: flex;
  padding: 0 24px 24px 24px;
  gap: 8px;
  background: #fff;
  border-top: 1px solid #e0e0e0;
}
.chat-input-bar input {
  flex: 1;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 10px 16px;
  font-size: 1rem;
  outline: none;
  transition: border 0.2s;
  box-shadow: inset 0 1px 2px rgba(0,0,0,0.03);
}
.chat-input-bar input:focus {
  border: 1.5px solid #3a7afe;
}
.chat-input-bar button {
  background: #3a7afe;
  color: #fff;
  border: none;
  border-radius: 8px;
  padding: 0 24px;
  font-size: 1rem;
  cursor: pointer;
  transition: background 0.2s;
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);
  font-weight: 500;
}
.chat-input-bar button:disabled {
  background: #b3cfff;
  cursor: not-allowed;
}
.chat-input-bar button:active {
  transform: translateY(1px);
  box-shadow: 0 0 2px rgba(0,0,0,0.05);
}
.chat-msg .content,
.ai-content {
  line-height: 1.8;
  letter-spacing: 0.03em;
  word-spacing: 0.1em;
}
.ai-content p {
  margin: 8px 0;
}
.ai-content ul, .ai-content ol {
  margin: 8px 0 8px 20px;
}
.ai-content li {
  margin-bottom: 4px;
}
.sidebar-loading, .loading-history {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 16px;
  color: #6b7280;
  font-size: 0.9rem;
}
.loading-history {
  flex-direction: column;
  padding: 32px 16px;
}
.loading-spinner {
  width: 20px;
  height: 20px;
  border: 2px solid #e6f0ff;
  border-top-color: #3a7afe;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 8px;
}
.load-more {
  padding: 10px;
  text-align: center;
  color: #3a7afe;
  font-size: 0.9rem;
  cursor: pointer;
  border-bottom: 1px solid #f0f0f0;
  background: #f7faff;
}
.load-more:hover {
  background: #e6f0ff;
}
@keyframes spin {
  to { transform: rotate(360deg); }
}
@media (max-width: 900px) {
  .chat-layout {
    flex-direction: column;
    height: 100vh;
    min-height: 100vh;
    max-width: 100vw;
  }
  .chat-sidebar {
    width: 100%;
    min-width: 0;
    border-right: none;
    border-bottom: 1px solid #e0e0e0;
    border-radius: 0;
    height: auto;
  }
  .chat-sidebar.closed {
    width: 36px;
    min-width: 36px;
  }
  .chat-main {
    border-radius: 0;
    height: auto;
  }
  .chat-container {
    padding: 0 8px;
  }
  .chat-title-bar {
    padding: 16px 8px 0 8px;
  }
  .chat-input-bar {
    padding: 0 8px 8px 8px;
  }
  .delete-btn {
    opacity: 1;
  }
}
.sidebar-conv.temp {
  background: #f9fafc;
  border-left: 3px solid #3a7afe;
}
.temp-badge {
  font-size: 0.75rem;
  padding: 2px 6px;
  background: #e6f0ff;
  color: #3a7afe;
  border-radius: 4px;
  margin-left: 8px;
}
.conv-click-area {
  display: flex;
  align-items: center;
  flex: 1;
  padding: 12px 16px;
  cursor: pointer;
  min-height: 44px;
  transition: background-color 0.2s;
}
.conv-click-area:hover {
  background-color: #f0f7ff;
}
.sidebar-conv.active .conv-click-area {
  background-color: #e6f0ff;
}
.assistant-selector {
  display: flex;
  justify-content: center;
  gap: 1.5rem;
  margin: 18px 0 8px 0;
}
.assistant-card {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  background: #f5f7fa;
  border-radius: 8px;
  padding: 0.7rem 1.5rem;
  font-size: 1.1rem;
  color: #3a7afe;
  cursor: pointer;
  border: 2px solid transparent;
  transition: border 0.2s, background 0.2s;
  box-shadow: 0 1px 3px rgba(0,0,0,0.05);
}
.assistant-card:hover {
  border: 2px solid #3a7afe;
  background: #e6f0ff;
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}
.assistant-card.selected {
  border: 2px solid #3a7afe;
  background: #e6f0ff;
  color: #2563eb;
  font-weight: bold;
}
.assistant-icon {
  font-size: 1.5rem;
}
.assistant-merge-bar {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  gap: 1rem;
  margin: 18px 0 8px 0;
  padding-left: 24px;
  position: relative;
}
.assistant-cancel-btn {
  background: none;
  border: none;
  color: #999;
  font-size: 1.5rem;
  cursor: pointer;
  margin-left: 12px;
  transition: color 0.2s;
}
.assistant-cancel-btn:hover {
  color: #f56565;
}
</style>
